//! Core type definitions for the AI-Native Code Agent

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use chrono::{DateTime, Utc};

/// Task representation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Task {
    pub id: String,
    pub request: String,
    pub status: TaskStatus,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub result: Option<TaskResult>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum TaskStatus {
    Pending,
    InProgress,
    Completed,
    Failed,
}

/// Task result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskResult {
    pub success: bool,
    pub summary: String,
    pub details: Option<String>,
    pub execution_time: Option<u64>,
    pub task_plan: Option<TaskPlan>,
}

/// Task plan generated by understanding engine
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TaskPlan {
    // Core AI planning fields
    pub understanding: String,
    pub approach: String,
    pub complexity: TaskComplexity,
    pub estimated_steps: Option<u32>,
    pub requirements: Vec<String>,
    
    // Structured execution fields (for detailed execution)
    /// Optional structured execution steps for more detailed execution
    pub structured_steps: Option<Vec<StructuredExecutionStep>>,
    /// Optional step dependencies for execution ordering
    pub step_dependencies: Option<Vec<StepDependency>>,
    
    // Service layer fields (for API responses)
    /// Simple steps derived from approach (for service layer compatibility)
    #[serde(default)]
    pub steps: Vec<String>,
    /// Required tools for execution
    #[serde(default)]
    pub required_tools: Vec<String>,
    /// Estimated time in seconds
    pub estimated_time: Option<u64>,
    /// Creation timestamp
    pub created_at: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TaskComplexity {
    Simple,    // Single step operation
    Moderate,  // Requires several steps
    Complex,   // Requires detailed planning
}

/// Execution context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionContext {
    pub task_id: String,
    pub plan: TaskPlan,
    pub current_step: u32,
    pub results: Vec<ExecutionStep>,
    pub variables: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionStep {
    pub step_number: u32,
    pub action: Action,
    pub result: Option<StepResult>,
    pub timestamp: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Action {
    pub action_type: ActionType,
    pub reasoning: String,
    pub confidence: f32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ActionType {
    UseTool {
        tool_name: String,
        arguments: HashMap<String, serde_json::Value>,
    },
    Think {
        reasoning: String,
    },
    Complete {
        summary: String,
    },
    AskClarification {
        question: String,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StepResult {
    pub success: bool,
    pub output: serde_json::Value,
    pub error: Option<String>,
    pub execution_time: u64,
}

/// Execution decision made by AI
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionDecision {
    pub action_type: ActionType,
    pub reasoning: String,
    pub confidence: f32,
}

/// Execution result
#[derive(Debug, Clone)]
pub struct ExecutionResult {
    pub success: bool,
    pub summary: String,
    pub details: String,
    pub execution_time: u64,
}

// ============================================================================
// Enhanced Executable Planning Types
// ============================================================================

/// Structured execution step with detailed execution information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StructuredExecutionStep {
    /// 步骤ID（用于依赖引用）
    pub id: String,
    /// 步骤名称
    pub name: String,
    /// 步骤描述
    pub description: String,
    /// 步骤类型
    pub step_type: StructuredStepType,
    /// 预估执行时间（分钟）
    pub estimated_duration: Option<u32>,
    /// 前置条件
    pub preconditions: Vec<String>,
    /// 预期输出
    pub expected_outputs: Vec<String>,
    /// 验证标准
    pub validation_criteria: Vec<String>,
    /// 失败时的回滚操作
    pub rollback_actions: Vec<String>,
}

/// 结构化步骤类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum StructuredStepType {
    /// 文件操作
    FileOperation {
        operation_type: FileOperationType,
        file_path: String,
        parameters: HashMap<String, serde_json::Value>,
    },
    /// 命令执行
    CommandExecution {
        command: String,
        arguments: Vec<String>,
        working_directory: Option<String>,
        environment: HashMap<String, String>,
    },
    /// 代码生成
    CodeGeneration {
        language: String,
        template: Option<String>,
        output_file: String,
        parameters: HashMap<String, serde_json::Value>,
    },
    /// 数据分析
    DataAnalysis {
        input_sources: Vec<String>,
        analysis_type: String,
        output_format: String,
        parameters: HashMap<String, serde_json::Value>,
    },
    /// 系统配置
    SystemConfiguration {
        config_type: String,
        config_file: String,
        settings: HashMap<String, serde_json::Value>,
    },
    /// 测试执行
    TestExecution {
        test_type: String,
        test_files: Vec<String>,
        test_framework: String,
        parameters: HashMap<String, serde_json::Value>,
    },
    /// 自定义工具调用
    ToolInvocation {
        tool_name: String,
        parameters: HashMap<String, serde_json::Value>,
    },
    /// 人工确认步骤
    ManualConfirmation {
        prompt: String,
        validation_type: String,
    },
}

/// 文件操作类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum FileOperationType {
    Create,
    Read,
    Update,
    Delete,
    Copy,
    Move,
    Search,
    Replace,
}

/// 步骤依赖关系
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StepDependency {
    /// 依赖的步骤ID
    pub step_id: String,
    /// 被依赖的步骤ID
    pub depends_on: String,
    /// 依赖类型
    pub dependency_type: DependencyType,
    /// 依赖条件
    pub condition: Option<String>,
}

/// 依赖类型
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DependencyType {
    /// 严格依赖：前置步骤必须成功完成
    StrictDependency,
    /// 弱依赖：前置步骤完成即可（无论成功失败）
    WeakDependency,
    /// 条件依赖：基于条件决定是否依赖
    ConditionalDependency,
    /// 数据依赖：需要前置步骤的输出数据
    DataDependency,
}

/// 执行进度跟踪
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionProgress {
    /// 任务ID
    pub task_id: String,
    /// 当前执行的步骤
    pub current_step: Option<String>,
    /// 已完成的步骤
    pub completed_steps: Vec<DetailedStepResult>,
    /// 失败的步骤
    pub failed_steps: Vec<DetailedStepResult>,
    /// 跳过的步骤
    pub skipped_steps: Vec<String>,
    /// 开始时间
    pub started_at: DateTime<Utc>,
    /// 更新时间
    pub updated_at: DateTime<Utc>,
    /// 总进度百分比
    pub progress_percentage: f32,
}

/// 详细的步骤执行结果
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetailedStepResult {
    /// 步骤ID
    pub step_id: String,
    /// 执行状态
    pub status: DetailedStepStatus,
    /// 开始时间
    pub started_at: DateTime<Utc>,
    /// 完成时间
    pub completed_at: Option<DateTime<Utc>>,
    /// 实际执行时间（毫秒）
    pub actual_duration: Option<u64>,
    /// 输出数据
    pub outputs: HashMap<String, serde_json::Value>,
    /// 错误信息
    pub error_message: Option<String>,
    /// 执行日志
    pub logs: Vec<String>,
}

/// 详细步骤执行状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DetailedStepStatus {
    /// 等待执行
    Pending,
    /// 正在执行
    Running,
    /// 执行成功
    Completed,
    /// 执行失败
    Failed,
    /// 被跳过
    Skipped,
    /// 需要人工干预
    RequiresIntervention,
}

// ============================================================================
// TaskPlan Extensions for Structured Execution
// ============================================================================

impl TaskPlan {
    /// 检查是否有结构化步骤
    pub fn has_structured_steps(&self) -> bool {
        self.structured_steps.as_ref().map_or(false, |steps| !steps.is_empty())
    }
    
    /// Create a TaskPlan with service layer fields populated
    pub fn with_service_fields(mut self) -> Self {
        // Populate steps from approach if empty
        if self.steps.is_empty() && !self.approach.is_empty() {
            self.steps = vec![self.approach.clone()];
        }
        
        // Set creation timestamp if not already set
        if self.created_at.is_none() {
            self.created_at = Some(Utc::now());
        }
        
        self
    }
    
    /// Convert approach to simple steps for service layer compatibility
    pub fn derive_steps_from_approach(&mut self) {
        if self.steps.is_empty() && !self.approach.is_empty() {
            self.steps = vec![self.approach.clone()];
        }
    }
    
    /// 获取可执行的下一个步骤
    pub fn get_next_executable_steps(&self, completed_steps: &[String]) -> Vec<&StructuredExecutionStep> {
        let steps = match &self.structured_steps {
            Some(steps) => steps,
            None => return vec![],
        };
        
        let empty_deps = vec![];
        let dependencies = self.step_dependencies.as_ref().unwrap_or(&empty_deps);
        
        steps
            .iter()
            .filter(|step| {
                // 检查步骤是否已完成
                if completed_steps.contains(&step.id) {
                    return false;
                }
                
                // 检查所有依赖是否满足
                let step_dependencies: Vec<_> = dependencies
                    .iter()
                    .filter(|dep| dep.step_id == step.id)
                    .collect();
                
                for dep in step_dependencies {
                    match dep.dependency_type {
                        DependencyType::StrictDependency => {
                            if !completed_steps.contains(&dep.depends_on) {
                                return false;
                            }
                        }
                        _ => {
                            // 其他依赖类型的处理逻辑
                            // 这里简化处理，实际可以根据需要扩展
                        }
                    }
                }
                
                true
            })
            .collect()
    }
    
    /// 验证计划的完整性
    pub fn validate_structured_plan(&self) -> Result<(), String> {
        let steps = match &self.structured_steps {
            Some(steps) => steps,
            None => return Ok(()), // 没有结构化步骤是可以的
        };
        
        let empty_deps = vec![];
        let dependencies = self.step_dependencies.as_ref().unwrap_or(&empty_deps);
        
        // 检查步骤ID是否唯一
        let mut step_ids = std::collections::HashSet::new();
        for step in steps {
            if !step_ids.insert(&step.id) {
                return Err(format!("Duplicate step ID: {}", step.id));
            }
        }
        
        // 检查依赖是否有效
        for dep in dependencies {
            if !step_ids.contains(&dep.step_id) {
                return Err(format!("Invalid dependency: step {} not found", dep.step_id));
            }
            if !step_ids.contains(&dep.depends_on) {
                return Err(format!("Invalid dependency: step {} not found", dep.depends_on));
            }
        }
        
        // 检查循环依赖
        if self.has_circular_dependencies() {
            return Err("Circular dependencies detected".to_string());
        }
        
        Ok(())
    }
    
    /// 检查是否存在循环依赖
    fn has_circular_dependencies(&self) -> bool {
        let dependencies = match &self.step_dependencies {
            Some(deps) => deps,
            None => return false,
        };
        
        // 简单的循环依赖检测算法
        for dep in dependencies {
            if self.has_path(&dep.depends_on, &dep.step_id) {
                return true;
            }
        }
        false
    }
    
    /// 检查从起始节点到目标节点是否存在路径
    fn has_path(&self, from: &str, to: &str) -> bool {
        let mut visited = std::collections::HashSet::new();
        self.dfs_path(from, to, &mut visited)
    }
    
    /// 深度优先搜索路径
    fn dfs_path(&self, current: &str, target: &str, visited: &mut std::collections::HashSet<String>) -> bool {
        if current == target {
            return true;
        }
        
        if visited.contains(current) {
            return false;
        }
        
        visited.insert(current.to_string());
        
        if let Some(dependencies) = &self.step_dependencies {
            for dep in dependencies {
                if dep.depends_on == current && self.dfs_path(&dep.step_id, target, visited) {
                    return true;
                }
            }
        }
        
        false
    }
    
    /// 估算总执行时间
    pub fn estimate_total_duration(&self) -> u32 {
        match &self.structured_steps {
            Some(steps) => steps
                .iter()
                .map(|step| step.estimated_duration.unwrap_or(10)) // 默认10分钟
                .sum(),
            None => self.estimated_steps.unwrap_or(1) * 10, // 传统估算，每步骤10分钟
        }
    }
    
    /// 生成执行计划摘要
    pub fn generate_execution_summary(&self) -> String {
        if let Some(steps) = &self.structured_steps {
            format!(
                "任务计划包含 {} 个结构化执行步骤，预计耗时 {} 分钟。复杂度：{:?}",
                steps.len(),
                self.estimate_total_duration(),
                self.complexity
            )
        } else {
            format!(
                "任务计划包含 {} 个传统步骤，预计耗时 {} 分钟。复杂度：{:?}",
                self.estimated_steps.unwrap_or(1),
                self.estimate_total_duration(),
                self.complexity
            )
        }
    }
}